<template>
    <div class="min-h-screen bg-[#F7F8FA] flex flex-col md:flex-row">
        <!-- 左侧导航栏 - 在移动端隐藏，在桌面端显示 -->
        <nav class="w-full md:w-[17.5rem] md:min-w-[17.5rem] md:h-screen bg-[#F8F9FA] flex flex-col">
            <NavTop class="md:block"></NavTop>
            <!-- 导航菜单 -->
            <div class="flex-1 flex flex-col space-y-1 p-4">
                <!-- 返回按钮 -->
                <div @click="router.back()" class="flex items-center mb-4">
                    <el-icon class="mr-2">
                        <Back />
                    </el-icon>
                    <span class="text-gray-900">个人中心</span>
                </div>

                <!-- 个人信息导航 -->
                <div class="text-sm text-gray-500 mb-2">个人信息</div>
                <router-link to="/profile" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-200"
                    :class="{ 'bg-gray-200': $route.path === '/profile' }">
                    <el-icon class="mr-2">
                        <User />
                    </el-icon>
                    <span class="text-gray-900">账户信息</span>
                </router-link>
            </div>
            <NavBottom class="hidden md:block flex-shrink-0"></NavBottom>
        </nav>

        <!-- 右侧主体内容 -->
        <div class="flex-1 bg-[#FFFFFF] p-4 md:p-8 flex flex-col items-center">
            <!-- 白色卡片容器 -->
            <div class="bg-white rounded-lg p-4 md:p-6 shadow-sm mb-6 w-full md:w-[800px] border border-[#dee2e6]">
                <h2 class="text-lg mb-4 md:mb-6">账户信息</h2>

                <!-- 账户信息表单 -->
                <div class="space-y-4 md:space-y-6">
                    <!-- 头像 -->
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2 md:gap-4">
                            <span class="text-gray-500 w-16">头像</span>
                            <img :src="userInfo.avatar" alt="头像" class="h-10 w-10 md:h-12 md:w-12 rounded-full">
                        </div>
                        <el-icon class="text-gray-400 cursor-pointer" @click="showAvatarDialog = true">
                            <Edit />
                        </el-icon>
                    </div>

                    <!-- 姓名 -->
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2 md:gap-4">
                            <span class="text-gray-500 w-16">姓名</span>
                            <span>{{ userInfo.username }}</span>
                        </div>
                        <el-icon class="text-gray-400 cursor-pointer" @click="showNameDialog = true">
                            <Edit />
                        </el-icon>
                    </div>

                    <!-- 密码 -->
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2 md:gap-4">
                            <span class="text-gray-500 w-16">修改密码</span>
                        </div>
                        <el-icon class="text-gray-400 cursor-pointer" @click="showPasswordDialog = true">
                            <Edit />
                        </el-icon>
                    </div>

                    <!-- 手机号 -->
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2 md:gap-4">
                            <span class="text-gray-500 w-12 md:w-16">手机号</span>
                            <div class="flex items-center">
                                <el-icon class="!text-green-500">
                                    <CircleCheck />
                                </el-icon>
                                <div class="pr-1 md:pr-2"></div>
                                <span class="mr-2 text-sm md:text-base">{{ userInfo.mobile }}</span>
                            </div>
                        </div>
                        <!-- <el-icon class="text-gray-400 cursor-pointer"><Edit /></el-icon> -->
                    </div>
                </div>
            </div>

            <!-- 修改头像弹窗 -->
            <el-dialog v-model="showAvatarDialog" title="修改头像" :width="isMobile ? '95%' : '480px'" align-center>
                <div class="flex flex-col items-center">
                    <el-upload class="w-full" drag action="#" :auto-upload="false" :on-change="handleAvatarChange"
                        accept=".jpg,.jpeg,.png,.gif">
                        <div class="text-center">
                            <el-icon class="text-2xl md:text-3xl text-gray-400">
                                <Plus />
                            </el-icon>
                            <div class="mt-2 text-xs md:text-sm text-gray-500">请选择上传5MB以内的JPG、GIF、PNG格式的图片</div>
                            <div class="text-xs text-gray-400">(点击或拖拽图片至此处)</div>
                        </div>
                    </el-upload>
                </div>
                <template #footer>
                    <div class="flex justify-end gap-2">
                        <el-button @click="showAvatarDialog = false">取消</el-button>
                        <el-button type="primary" @click="handleUpdateAvatar">保存</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 修改昵称弹窗 -->
            <el-dialog v-model="showNameDialog" title="修改昵称" :width="isMobile ? '95%' : '480px'" align-center>
                <div class="px-2 md:px-4">
                    <el-input v-model="newName" placeholder="请输入昵称" maxlength="15" show-word-limit />
                </div>
                <template #footer>
                    <div class="flex justify-end gap-2">
                        <el-button @click="showNameDialog = false">取消</el-button>
                        <el-button type="primary" @click="handleUpdateName">保存</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 修改密码弹窗 -->
            <el-dialog v-model="showPasswordDialog" title="修改密码" :width="isMobile ? '95%' : '480px'" align-center>
                <div class="px-2 md:px-4">
                    <el-form :model="passwordForm" label-width="80px" class="space-y-4">
                        <!-- 手机号（不可修改） -->
                        <el-form-item label="手机号">
                            <el-input v-model="userInfo.mobile" disabled></el-input>
                        </el-form-item>

                        <!-- 验证码 -->
                        <el-form-item label="验证码">
                            <div class="flex gap-2">
                                <el-input v-model="passwordForm.code" placeholder="请输入验证码"></el-input>
                                <el-button :disabled="countdown > 0" @click="sendCode" class="w-32 !flex-shrink-0">
                                    {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
                                </el-button>
                            </div>
                        </el-form-item>

                        <!-- 新密码 -->
                        <el-form-item label="新密码">
                            <el-input v-model="passwordForm.password" type="password" placeholder="请输入新密码"
                                show-password>
                            </el-input>
                        </el-form-item>
                        <!-- 确认密码 -->
                        <el-form-item label="确认密码">
                            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
                                show-password>
                            </el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="flex justify-end gap-2">
                        <el-button @click="showPasswordDialog = false">取消</el-button>
                        <el-button type="primary" @click="handleUpdatePassword">确认</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 注销区域 -->
            <div class="bg-white rounded-lg p-4 md:p-6 shadow-sm w-full md:w-[800px] border border-[#dee2e6]">
                <!-- <h2 class="text-lg mb-2 md:mb-4">注销</h2>
                <p class="text-gray-500 text-xs md:text-sm mb-4">账户可以随时注销，注销后将无法恢复。注销账户后，您将无法继续使用该账户，您的所有数据将被删除。</p> -->
                <button
                    class="text-red-500 text-xs md:text-sm border border-solid border-red-500 px-3 py-1 md:px-4 md:py-2 rounded hover:bg-red-50"
                    @click="outLogin">
                    退出登录
                </button>
            </div>
        </div>
    </div>
</template>
<script setup>
import NavBottom from '@/components/nav/bottom.vue'
import NavTop from '@/components/nav/top.vue'
import defaultAvatar from '@/assets/images/avatar.png'
import { userApi } from '@/api'
import { User, Back, Edit,CircleCheck,Plus } from '@element-plus/icons-vue'
import { ref,onMounted,onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import uploader from '@/utils/upload'
import { getUserInfo } from '@/utils/auth'

// 添加移动端判断
const isMobile = ref(window.innerWidth < 768)

const router = useRouter();
const showAvatarDialog = ref(false)
const showNameDialog = ref(false)
const newName = ref('Chasel')
// 头像上传相关
const avatarFile = ref(null)

// 判断头像
const imgUrl = import.meta.env.VITE_IMG_BASE_URL || ''


// 修改密码相关
const showPasswordDialog = ref(false)
const countdown = ref(0)
const passwordForm = ref({
    code: '',
    password: '',
    confirmPassword: ''
})

// 获取用户信息
const userInfo = ref({
    username: '',
    mobile: '',
    avatar_url: '',
    avatar: '',
    // ... 其他用户信息
})

// 头像改变事件
const handleAvatarChange = (file) => {
    const isImage = file.raw.type.startsWith('image/')
    const isLt5M = file.raw.size / 1024 / 1024 < 5

    if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB！')
        return false
    }

    avatarFile.value = file.raw
}

// 更新头像
const handleUpdateAvatar = async () => {
    if (!avatarFile.value) {
        ElMessage.warning('请选择要上传的头像')
        return
    }

    try {
        // 先上传图片获取URL
        const avatarUrl = await uploader.uploadImageWithCompression(avatarFile.value)
        
        const userInfoObj = getUserInfo()
        
        // 调用更新用户信息接口
        await userApi.updateUserInfo({
            avatar_url: avatarUrl,
            username: userInfo.value.username
        })
        
        ElMessage.success('头像修改成功')
        showAvatarDialog.value = false

        // 更新本地存储的用户信息
        userInfoObj.avatar = imgUrl + avatarUrl
        userInfoObj.avatar_url = avatarUrl
        localStorage.setItem('userInfo', JSON.stringify(userInfoObj))
        return userInfo.value = userInfoObj
        
    } catch (error) {
        ElMessage.error({
            message: '头像修改失败',
            duration: 5000
        })
    }
}

// 更新昵称
const handleUpdateName = async () => {
    if (!newName.value) {
        ElMessage.warning('请输入昵称')
        return
    }

    try {
        const userInfoObj = getUserInfo()

        await userApi.updateUserInfo({
            username: newName.value,
            avatar_url: userInfo.value.avatar_url || null
        })
        
        ElMessage.success('昵称修改成功')
        showAvatarDialog.value = false

        // 更新本地存储的用户信息
        userInfoObj.avatar = imgUrl + avatarUrl
        userInfoObj.avatar_url = avatarUrl
        localStorage.setItem('userInfo', JSON.stringify(userInfoObj))
        return userInfo.value = userInfoObj

    } catch (error) {
        ElMessage.error({
            message: '昵称修改失败',
            duration: 5000
        })
    }
}

// 初始化用户信息
onMounted(() => {
    const userInfoStr = getUserInfo()
    if (userInfoStr) {
        userInfo.value = userInfoStr
    }
    // console.log(userInfo.value)
    if (!userInfo.value.avatar_url || userInfo.value.avatar_url === 'null') {
        userInfo.value.avatar = defaultAvatar
    } else {
        userInfo.value.avatar = imgUrl + userInfo.value.avatar_url
    }
    newName.value = userInfo.value.username
    
    window.addEventListener('resize', () => {
        isMobile.value = window.innerWidth < 768
    })
})
// 组件卸载时移除监听
onUnmounted(() => {
    window.removeEventListener('resize', () => {
        isMobile.value = window.innerWidth < 768
    })
})

// 发送验证码
const sendCode = async () => {
    try {
        await userApi.loginSms(userInfo.value.mobile)
        ElMessage.success('验证码发送成功')
        // 开始倒计时
        countdown.value = 60
        const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    } catch (error) {
        ElMessage.error('验证码发送失败')
    }
}

// 修改密码
const handleUpdatePassword = async () => {
    if (!passwordForm.value.code || !passwordForm.value.password || !passwordForm.value.confirmPassword) {
        ElMessage.warning('请填写完整信息')
        return
    }
    
    // 校验两次密码是否一致
    if (passwordForm.value.password !== passwordForm.value.confirmPassword) {
        ElMessage.warning('两次输入的密码不一致')
        return
    }
    try {
        await userApi.updateUserPassword({
            code: passwordForm.value.code,
            pwd: passwordForm.value.password
        })
        
        ElMessage.success('密码修改成功')
        showPasswordDialog.value = false
        // 清空表单
        passwordForm.value = {
            code: '',
            password: '',
            confirmPassword: ''
        }
        // 返回上一页
        router.back()
    } catch (error) {
        ElMessage.error('密码修改失败')
    }
}


// 退出登录
const outLogin = async () => {
    try {
        await userApi.logout()

        localStorage.removeItem('userInfo')
        localStorage.removeItem('Authorization')

        ElMessage.success('操作成功')
        setTimeout(() => {
            router.push('/login')
        }, 2000)

    } catch (error) {
        ElMessage.error('操作失败，请重试')
    }
}
</script>